import { Application, IBoot } from "egg";
import * as assert from "assert";
import { createConnection } from "mongoose";
import { join } from "path";

export default class AppBoot implements IBoot {
  private readonly app: Application;
  constructor(app: Application) {
    this.app = app;
    // session设置
    /* app.sessionMap = {};
    app.sessionStore = {
      async get(key) {
        app.logger.info("key", key);
        return app.sessionMap[key];
      },
      async set(key, value) {
        app.logger.info("key", key);
        app.logger.info("value", value);
        app.sessionMap[key] = value;
      },
      async destroy(key) {
        delete app.sessionMap[key];
      },
    }; */
    /* const { url } = this.app.config.mongoose;
    assert(url, "[egg-mongoose] url is required on config");
    const db = createConnection(url);
    db.on("connected", () => {
      app.logger.info(`[egg-mongoose] ${url} connected successfully`);
    });
    app.mongoose = db; */
  }

  configWillLoad(): void {
    // 此时config文件以及被读取并合并，但是还并未生效
    // 这是应用层修改配置的最后时机
    // 应用场景:加解密
    // console.log("config", this.app.config.baseUrl);
    // console.log("enable middleware", this.app.config.coreMiddleware);
    // this.app.config.coreMiddleware.unshift("myLogger");
  }

  configDidLoad(): void {
    // 配置插件加载完成(configDidLoad)同步
  }

  async didLoad(): Promise<void> {
    // 文件加载完成(didLoad)异步
  }

  async willReady(): Promise<void> {
    // 插件启动完毕(wiillRead)异步
    // console.log("enable willready", this.app.config.coreMiddleware);
    /* const dir = join(this.app.config.baseDir, "app/model");
    this.app.loader.loadToApp(dir, "model", {
      caseStyle: "upper",
    }); */
  }

  async didReady(): Promise<void> {
    // 应用已经启动完毕(didReady)异步
    // const ctx = await this.app.createAnonymousContext();
    // const res = await ctx.service.test.sayHi("LL");
    // console.log("did ready res", res);
    // console.log("final middleware", this.app.middleware);
  }

  async serverDidReady(): Promise<void> {
    // http / https server 已启动, 开始接受外部请求
  }
}
